package com.zhangxiaofanfan.hotcode.third;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-29 08:21:44
 */
public class HotCode031 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        HotCode031 hotCode = new HotCode031();
        hotCode.reverseKGroup(head, 2);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || k <= 1) {
            return head;
        }
        Stack<ListNode> stack = new Stack<>();
        ListNode header = new ListNode();
        header.next = head;
        ListNode index1 = header;
        ListNode index2 = index1.next;
        ListNode index3;
        boolean end = false;
        while (true) {
            for (int i = 0; i < k; i++) {
                if (index2 == null) {
                    end = true;
                    break;
                }
                stack.push(index2);
                index2 = index2.next;
            }
            if (end) {
                break;
            }
            index3 = index2;
            // 需要进行翻转
            index2 = index1;
            while (!stack.isEmpty()) {
                index2.next = stack.pop();
                index2 = index2.next;
            }
            index2.next = index3;
            index1 = index2;
            index2 = index1.next;
        }
        return header.next;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
